<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      padding: 0;
      margin: 0;
    }

    .wrap {
      width: 300px;
      height: 400px;
      background-color: grey;
      border: 1px solid #333;
      margin: 50px auto;
      position: relative;
    }

    .sub {
      width: 50px;
      height: 50px;
      background-color: pink;
      position: absolute;
      left: 100px;
      top: 200px;
    }
  </style>
</head>

<body>
  <div class="wrap">
    <div class="sub"></div>
  </div>
</body>
<script>

  // ←  37
  // ↑  38
  // →  39
  // ↓  40

  // A  65
  // W  87
  // D  68
  // S  83

  var wrap = document.getElementsByClassName("wrap")[0];
  var sub = document.getElementsByClassName("sub")[0];

  var maxLeft = wrap.clientWidth - sub.clientWidth;
  var maxTop = wrap.clientHeight - sub.clientHeight;

  document.onkeydown = function (e) {
    var e = e || window.event;
    var keyCode = e.which || e.keyCode;
    console.log(e.key, keyCode);

    var x;
    var y;
    var speed = 10;
    if (keyCode == 37 || keyCode == 65) { //左
      console.log("左");
      x = sub.offsetLeft - speed;
    } else if (keyCode == 38 || keyCode == 87) { //上
      console.log("上");
      y = sub.offsetTop - speed;
    } else if (keyCode == 39 || keyCode == 68) { //右
      console.log("右");
      x = sub.offsetLeft + speed;
    } else if (keyCode == 40 || keyCode == 83) { //下
      console.log("下");
      y = sub.offsetTop + speed;
    }

    // 移动之前判断 是否超出临界值 (小于最小值  大于最大值)
    if (x < 0) x = 0;
    if (x > maxLeft) x = maxLeft;
    if (y < 0) y = 0;
    if (y > maxTop) y = maxTop;

    sub.style.left = x + "px";
    sub.style.top = y + "px";
  }




</script>

</html>